﻿using FunctionLib.DBOperator;
using FunctionLib.Help;
using InfluxData.Net.InfluxDb.Models.Responses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunctionLib.Single
{
    /// <summary>
    /// params:
    /// 0:sourceId obj
    /// 1:quantityId obj
    /// 2:date num
    /// 3:hour num
    /// 4:calcType num
    /// </summary>
    public class PMEGetHourData : IFunction
    {
        public string Name => "PMEGetHourData";

        public int MinParam => 5;

        public int MaxParam => 5;

        public object Calc(params object[] param)
        {
			object result;
			try
			{
				if (param.Length < 5)
				{
					result = "参数数量错误";
				}
				else if (param[0] == null || param[1] == null)
				{
					result = "参数值1、2为空";
				}
				else
				{
					for (int i = 4; i <= 5; i++)
					{
						if (i != 2)
						{
							string checkRes = QueryHelp.NumCheck(param[i - 1]);
							if (checkRes != null)
							{
								return checkRes + ":" + i.ToString();
							}
						}
					}
					DateTime temp;
					if (param[2].GetType() == typeof(double) || param[2].GetType() == typeof(int))
					{
						temp = new DateTime(1899, 12, 30).AddDays(Convert.ToDouble(param[2]));
					}
					else if (!DateTime.TryParse(param[2].ToString(), out temp))
					{
						return "参数3错误";
					}
					object sourceId = param[0];
					object quantityId = param[1];
					double hour = Convert.ToDouble(param[3]);
					string dateFront = temp.AddHours(hour).ToString("yyyy-MM-dd HH:mm:ss");
					string dateAfter = temp.AddHours(hour + 1.0).ToString("yyyy-MM-dd HH:mm:ss");
					int calcTypeInt = -1;
					string calcType = QueryHelp.GetCalcType(param[4], ref calcTypeInt);
					string equeEndStr = QueryHelp.IsWithEndEque(calcTypeInt) ? "=" : "";
					string queryString = string.Format("select {0} from {1} where time >= '{2}' and time<{3}'{4}' and SourceID = '{5}' and QuantityID = '{6}'", new object[]
					{
						calcType,
						PublicDef.DBTableName,
						dateFront,
						equeEndStr,
						dateAfter,
						sourceId,
						quantityId
					});
					Serie[] res2 = InfluxDBClient.CreatDBClient().ExecuteQuery(queryString);
					DateTime time = default(DateTime);
					object res = QueryHelp.GetResult(res2, ref time);
					result = FunctionHelp.GetFunctionReturnResult(calcTypeInt, time, (res.GetType() != typeof(double) || double.IsNaN(Convert.ToDouble(res))) ? 0.0 : Convert.ToDouble(res));
				}
			}
			catch (Exception ex)
			{
				result = ex.Message;
			}
			return result;
		}

    }
}
